package com.winit.openapi.wop.inbound.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.filter.SearchFilterHelper;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.pms.spi.winit.WinitProductService;
import com.winit.pms.spi.winit.WinitRuleService;
import com.winit.pms.spi.winit.command.WinitProductQueryCommand;
import com.winit.pms.spi.winit.command.WinitRuleQueryCommand;
import com.winit.pms.spi.winit.vo.WinitProduct;
import com.winit.pms.spi.winit.vo.WinitRule;
import com.winit.ums.spi.CustomerAddressService;
import com.winit.ums.spi.commnad.CustomerAddressQueryCommand;
import com.winit.ums.spi.vo.CustomerAddress;

@Controller
@RequestMapping(value = "/winit/ums")
public class WHInboundAddressController extends BaseController {

    @Resource
    private CustomerAddressService customerAddressService;

    @Resource
    private WinitRuleService       winitRuleService;

    @Resource
    private WinitProductService    winitProductService;

    /**
     * 按userID与productCode和dispatchCode查询可提货地址接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return String
     * @author peipei.zeng
     */
    @RequestMapping(value = "/getPickupAddress")
    public String getPickupAddress(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        CustomerAddressQueryCommand command = new CustomerAddressQueryCommand();
        Searchable<?> searchable = Searchable.newSearchable();
        searchable.addSort(new Sort(Sort.Direction.DESC, "ID"));
        command.setCtx(CommandContext.getContext());
        command.setUserId(Long.parseLong(CommandContext.getContext().getUserId()));
        Object params = requestMsg.getData();

        JSONObject json = null;
        if (params instanceof JSONObject) {
            json = (JSONObject) params;

            if (json.containsKey("pageParams")) {
                ValidateUtil.validNotNull(json.getJSONObject("pageParams"), "pageSize");
                ValidateUtil.validNotNull(json.getJSONObject("pageParams"), "pageNo");
                ValidateUtil.validInteger(json.getJSONObject("pageParams"), "pageSize", true);
                ValidateUtil.validInteger(json.getJSONObject("pageParams"), "pageNo", true);

            }

            int pageNo = 1, pageSize = 10; // 分页参数
            if (ValidateUtil.isExistValue(json, "pageParams")) {
                JSONObject pageParam = json.getJSONObject("pageParams");
                if (ValidateUtil.isExistValue(pageParam, "pageNo")) {
                    pageNo = pageParam.getIntValue("pageNo") == 0 ? 1 : pageParam.getIntValue("pageNo");

                }
                if (ValidateUtil.isExistValue(pageParam, "pageSize")) {
                    pageSize = pageParam.getIntValue("pageSize");
                }
            }
            searchable.setPage(pageNo - 1, pageSize);
        } else {
            throw new ApiException(ErrorCode.ILLEGAL_JSON_STRING);
        }
        searchable.and(SearchFilterHelper.newCondition("user_id", SearchOperator.eq, command.getUserId()));
        searchable.and(SearchFilterHelper.newCondition("isdelete", SearchOperator.ne, "Y"));
        command.setSearchable(searchable);
        Page<CustomerAddress> addresses = customerAddressService.queryCustomerAddress(command);

        List<CustomerAddress> list = addresses.content;

        if (json.containsKey("winitProductCode")) {
            String winitProductCode = json.getString("winitProductCode");
            if (list != null && isNeedSwapLanguage(winitProductCode)) {
                for (CustomerAddress customerAddress : list) {
                    if (ApiConstant.COUNTRY_CODE_CN.equals(customerAddress.getCountryCode())) {
                        customerAddress.setStateName(customerAddress.getState());
                        customerAddress.setCityName(customerAddress.getCityCode());
                        customerAddress.setDetailCn(customerAddress.getDetailEn());
                        customerAddress.setDistrictName(customerAddress.getDistrictCode());
                        customerAddress.setContactPerson(customerAddress.getContactPersonEn());
                    }
                }
            }
        }
        List<Map<String, String>> addressList = new ArrayList<Map<String, String>>();
        if (CollectionUtils.isNotEmpty(list)&&null!=list) {
            for (CustomerAddress customerAddress : list) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("addressCode", customerAddress.getCode());
                map.put("isDefault", customerAddress.getIsdefault());
                map.put("countryName", customerAddress.getCountryName());
                map.put("stateName", customerAddress.getStateName());
                map.put("cityName", customerAddress.getCityName());
                map.put("districtName", customerAddress.getDistrictName());
                map.put("street", "");
                map.put("address", customerAddress.getDetailCn());
                map.put("zipCode", customerAddress.getPostCode());
                map.put("houseNo", customerAddress.getDoorplate());
                map.put("contactPerson", customerAddress.getContactPerson());
                map.put("contactPhone", customerAddress.getContactNumber());
                map.put("email", customerAddress.getEmail());
                map.put("addressline1", customerAddress.getDetail1());
                map.put("addressline2", customerAddress.getDetail2());
                addressList.add(map);

            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        Map<String, Object> page = new HashMap<String, Object>();
        page.put("pageNo", addresses.getPageable().getPageNumber() + 1);
        page.put("pageSize", addresses.getPageable().getPageSize());
        page.put("totalCount", addresses.total);
        data.put("addressList", addressList);
        data.put("pageParams", page);
        responseMsg.setData(data);
        return SUCCESS;
    }

    private boolean isNeedSwapLanguage(String productCode) {
        WinitProductQueryCommand prodocutQComand = new WinitProductQueryCommand();
        prodocutQComand.setCode(productCode);
        WinitProduct winitProduct = winitProductService.queryProduct(prodocutQComand);
        if (winitProduct != null) {
            WinitRuleQueryCommand winitRuleQ = new WinitRuleQueryCommand();
            winitRuleQ.setWinitProductId(winitProduct.getWinitProductId());
            winitRuleQ.setRuleName(ApiConstant.RULE_NAME_LANG);
            winitRuleQ.setRuleAttribute(ApiConstant.RULE_ATTRIBUTE_SHIPPER_ADDR);
            WinitRule winitRule = winitRuleService.getWinitRuleByProductIdAndName(winitRuleQ);
            if (winitRule != null && winitRule.getRuleValue() != null
                && ApiConstant.LANGUAGE_EN_US.indexOf(winitRule.getRuleValue()) > -1) {
                return true;
            }
        }
        return false;
    }

}
